package cn.winstone.handler;

import cn.winstone.config.Config;
import cn.winstone.scanner.impl.ResourceScannerImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Winstone
 * @date 2020/7/28 - 9:32 下午
 */
public class RequestHandler {
    public static String BASE_URI = Config.BASE_URI;

    ResourceScannerImpl scanner = new ResourceScannerImpl(BASE_URI);

    private Map<String, String> map;


    public RequestHandler(InputStream stream) {
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        try {
            String str = bufferedReader.readLine();
            String method = str.substring(0, str.indexOf(" /"));
            String uri = str.substring(str.indexOf(" /")+1, str.lastIndexOf('H') - 1);
            String version = str.substring(str.indexOf("H"));


            map.put("method", method);
            map.put("uri", uri);
            map.put("version", version);

        } catch (IOException e) {
            e.printStackTrace();
        }
        this.map = map;
    }

    public String getMethod() {
        return map.get("method");
    }

    public String getURI() {
        return map.get("uri");
    }

    public String getVersion() {
        return map.get("version");
    }

    public static String getValue(InputStream stream, String key) throws IOException {
        String str = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        while ((str = bufferedReader.readLine()) != null) {
            if (str.toLowerCase().equals(key)) {
                return str.substring(str.indexOf(':') + 1);
            }
        }
        return null;
    }


}
